package com.purplesoft.zettl.Listener;

import com.purplesoft.zettl.R;
import com.purplesoft.zettl.Activities.EditItem;
import com.purplesoft.zettl.Adapters.ItemListAdapter;
import com.purplesoft.zettl.Database.DatabaseExecuter;
import com.purplesoft.zettl.DatabaseViews.VwItems;
import com.purplesoft.zettl.DatabaseViews.VwPurchaseItems;
import com.purplesoft.zettl.Utilities.Item;
import com.purplesoft.zettl.Utilities.ProgressBarItems;
import com.purplesoft.zettl.Utilities.SharedPrefs;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ZettlGestureListener extends SimpleOnGestureListener implements OnTouchListener {

	private Context context;
    private GestureDetector gDetector;
	private Cursor csVwPurchaseItems;
	private ListView lvZettl;
	private ItemListAdapter laItems;
	
    private int padding = 0;
    private int scroll = 0;
    private int initialX = 0;
    private int initialY = 0;
    private int currentX = 0;
    private int currentY = 0;
    private int pos, adapterPos;
    private int moveX = 0, moveY = 0;
    
    private boolean itemSwiped = false;
    
    private int displayWidth;
    private int itemCheckWidth, itemAlphaWidth = 0, itemAlpha = 255;
    private float itemAlphaWidthFactor;
    
    private Item item;
    private ItemListAdapter itemListAdapter;
    
    private ImageView ivItem;
    private TextView tvAddRemoveItem, tvCategoryColor, tvItem, tvAmountMeasure, tvItemDescriptionManufacturer, tvCategory, tvPriceMeasure;
    private DatabaseExecuter dbExec;
    private SharedPrefs sharedPrefs;
    
    private final int DEFAULT_VALUE = -99;
    
    public ZettlGestureListener()
    {
        super();
    }

    public ZettlGestureListener(Context context, ListView lvZettl) {
        this(context, null, lvZettl);
    }

    public ZettlGestureListener(Context context, GestureDetector gDetector, ListView lvZettl) {

        if(gDetector == null)
            gDetector = new GestureDetector(context, this);

        this.context = context;
        this.gDetector = gDetector;
		this.lvZettl = lvZettl;
		
		dbExec = new DatabaseExecuter(context);
		sharedPrefs = new SharedPrefs(context);
        
        DisplayMetrics displaymetrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        displayWidth = displaymetrics.widthPixels;
        itemCheckWidth = (int) (displayWidth * 0.5);
        itemAlphaWidthFactor = (float) 255/itemCheckWidth;

    }


    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

        return super.onFling(e1, e2, velocityX, velocityY);
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {

        return super.onSingleTapConfirmed(e);
    }

	
	@Override
	public boolean onDoubleTap(MotionEvent e) {
		int position = lvZettl.pointToPosition((int) e.getX(), (int) e.getY());
		if (position != -1) {
			String item = getItem(position);
			startEditItem(item);
		}
		return super.onDoubleTap(e);
	}

    private String getItem(int position) {
    	csVwPurchaseItems = dbExec.queryFromVwPurchaseItems(VwPurchaseItems.Columns.ListID, sharedPrefs.getInt(context.getResources().getString(R.string.zettl_current_list_id), DEFAULT_VALUE));
		laItems = new ItemListAdapter(context, csVwPurchaseItems);
		csVwPurchaseItems = (Cursor) laItems.getItem(position);
		int ciItem = csVwPurchaseItems.getColumnIndex(VwItems.Columns.Item);
		String item = csVwPurchaseItems.getString(ciItem);
		return item;
	}

	public boolean onTouch(View v, MotionEvent event) {

        if ( event.getAction() == MotionEvent.ACTION_DOWN)
        {
            padding = 0;
            initialX = (int) event.getX();
            initialY = (int) event.getY();
            currentX = (int) event.getX();
            currentY = (int) event.getY();
            adapterPos = lvZettl.pointToPosition((int) event.getX(),(int) event.getY());
            int firstViewItemIndex = lvZettl.getFirstVisiblePosition();
            pos = adapterPos - firstViewItemIndex;
        }

        if ( event.getAction() == MotionEvent.ACTION_MOVE)
        {
        	currentY = (int) event.getY();
        	scroll = currentY - initialY;
            currentX = (int) event.getX();
            padding = currentX - initialX;
            
            if ((scroll > 20 || scroll < -20) && moveY == 0 && moveX == 0) {
            	moveY = 1;
            }
            if ((padding > 20 || padding < -20) && moveY == 0 && moveX == 0) {
            	moveX = 1;
            }
        }
        
        if ( event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL)
        {
            if ((padding > itemCheckWidth) && itemSwiped == true) {
            	String ItemName = getItem(adapterPos);
        		DatabaseExecuter dbExec = new DatabaseExecuter(context);
        		item = dbExec.setItemAllAttributesFromCsVwPurchaseItems(ItemName);
        		dbExec.insertIntoTblCart(item);
        		dbExec.deleteFromTblPurchase(item);
        		ProgressBarItems progressBarItems = new ProgressBarItems();
    			progressBarItems.calculateItems(context);
    			csVwPurchaseItems = dbExec.queryFromVwPurchaseItems(VwPurchaseItems.Columns.ListID, sharedPrefs.getInt(context.getResources().getString(R.string.zettl_current_list_id), DEFAULT_VALUE));
    			itemListAdapter = new ItemListAdapter(context, csVwPurchaseItems);
    			lvZettl.setAdapter(itemListAdapter);
            	Toast.makeText(context, "'" + ItemName + "' " + context.getResources().getString(R.string.added_to_cart), Toast.LENGTH_SHORT).show();
            } else if ((padding < itemCheckWidth * -1) && itemSwiped == true) {
            	String ItemName = getItem(adapterPos);
        		DatabaseExecuter dbExec = new DatabaseExecuter(context);
        		item = dbExec.setItemAllAttributesFromCsVwPurchaseItems(ItemName);
        		dbExec.deleteFromTblPurchase(item);
        		ProgressBarItems progressBarItems = new ProgressBarItems();
    			progressBarItems.calculateItems(context);
    			csVwPurchaseItems = dbExec.queryFromVwPurchaseItems(VwPurchaseItems.Columns.ListID, sharedPrefs.getInt(context.getResources().getString(R.string.zettl_current_list_id), DEFAULT_VALUE));
    			itemListAdapter = new ItemListAdapter(context, csVwPurchaseItems);
    			lvZettl.setAdapter(itemListAdapter);
            	Toast.makeText(context, "'" + ItemName + "' " + context.getResources().getString(R.string.removed_from_list), Toast.LENGTH_SHORT).show();
            	
            } else {
            	if (moveX == 1) {
                	v =  lvZettl.getChildAt(pos);
                	if (v != null) {
                		tvAmountMeasure.setTextColor(Color.argb(255, 0, 0, 0));
                		tvPriceMeasure.setTextColor(Color.argb(255, 0, 0, 0));
                		tvItem.setTextColor(Color.argb(255, 0, 0, 0));
                		tvItemDescriptionManufacturer.setTextColor(Color.argb(255, 0, 0, 0));
                		tvCategory.setTextColor(Color.argb(255, 0, 0, 0));
                		ivItem.setAlpha(255);
                		tvCategoryColor.getBackground().setAlpha(255);
                		v.setBackgroundColor(Color.argb(0, 0, 210, 10));
                		v.scrollTo(0, 0);
                		tvAmountMeasure.setVisibility(View.VISIBLE);
                		tvPriceMeasure.setVisibility(View.VISIBLE);
                		tvItem.setVisibility(View.VISIBLE);
                		tvItemDescriptionManufacturer.setVisibility(View.VISIBLE);
                		tvCategory.setVisibility(View.VISIBLE);
                		ivItem.setVisibility(View.VISIBLE);
                		tvCategoryColor.setVisibility(View.VISIBLE);
                		tvAddRemoveItem.setVisibility(View.INVISIBLE);
                	}
            	}
            }
        	padding = 0;
        	initialX = 0;
        	initialY = 0;
        	currentX = 0;
        	currentY = 0;
        	moveX = 0;
        	moveY = 0;
        	itemSwiped = false;
        }

//        long eventDuration = event.getEventTime() - event.getDownTime();

        if (moveX == 1) {
        	if (scroll > 0) {
        		event.setAction(MotionEvent.ACTION_CANCEL);
        	} else if (scroll < 0) {
        		event.setAction(MotionEvent.ACTION_CANCEL);
        	}
        	
        	v =  lvZettl.getChildAt(pos);
        	if (v != null) {
        		tvAmountMeasure = (TextView) v.findViewById(R.id.tvAmountMeasure);
        		tvPriceMeasure = (TextView) v.findViewById(R.id.tvPriceMeasure);
        		tvItem = (TextView) v.findViewById(R.id.tvItem);
        		tvItemDescriptionManufacturer = (TextView) v.findViewById(R.id.tvItemDescriptionManufacturer);
        		tvCategory = (TextView) v.findViewById(R.id.tvCategory);
        		ivItem = (ImageView) v.findViewById(R.id.ivItem);
        		tvCategoryColor = (TextView) v.findViewById(R.id.tvCategoryColor);
        		tvAddRemoveItem = (TextView) v.findViewById(R.id.tvAddRemoveItem);
        		
        		if (padding > 0) {
        			itemAlphaWidth = (int) (padding * itemAlphaWidthFactor);
        			itemAlpha = 255 - itemAlphaWidth;
        			
        			if (itemAlpha <= 0) {
        				tvAmountMeasure.setTextColor(Color.argb(0, 0, 0, 0));
        				tvPriceMeasure.setTextColor(Color.argb(0, 0, 0, 0));
        				tvItem.setTextColor(Color.argb(0, 0, 0, 0));
        				tvItemDescriptionManufacturer.setTextColor(Color.argb(30, 0, 0, 0));
        				tvCategory.setTextColor(Color.argb(0, 0, 0, 0));
        				ivItem.setAlpha(0);
        				tvCategoryColor.getBackground().setAlpha(0);
        			} else {
        				tvAmountMeasure.setTextColor(Color.argb(itemAlpha, 0, 0, 0));
        				tvPriceMeasure.setTextColor(Color.argb(itemAlpha, 0, 0, 0));
        				tvItem.setTextColor(Color.argb(itemAlpha, 0, 0, 0));
        				tvItemDescriptionManufacturer.setTextColor(Color.argb(itemAlpha, 0, 0, 0));
        				tvCategory.setTextColor(Color.argb(itemAlpha, 0, 0, 0));
        				ivItem.setAlpha(itemAlpha);
        				tvCategoryColor.getBackground().setAlpha(itemAlpha);
        			}
        			
        			if (itemAlphaWidth >= 255) {
        				itemAlphaWidth = 255;
        				itemSwiped = true;
        				
        				tvAmountMeasure.setVisibility(View.INVISIBLE);
        				tvPriceMeasure.setVisibility(View.INVISIBLE);
        				tvItem.setVisibility(View.INVISIBLE);
        				tvItemDescriptionManufacturer.setVisibility(View.INVISIBLE);
        				tvCategory.setVisibility(View.INVISIBLE);
        				ivItem.setVisibility(View.INVISIBLE);
        				tvCategoryColor.setVisibility(View.INVISIBLE);
        				
        				v.scrollTo(0, 0);
        				
        				tvAddRemoveItem.setText(tvItem.getText().toString() + "\n" + context.getResources().getString(R.string.add_to_cart));
        				tvAddRemoveItem.setVisibility(View.VISIBLE);
        			} else {
        				tvAddRemoveItem.setVisibility(View.INVISIBLE);
        				v.scrollTo(padding * -1, 0);
        				
        				tvAmountMeasure.setVisibility(View.VISIBLE);
        				tvPriceMeasure.setVisibility(View.VISIBLE);
        				tvItem.setVisibility(View.VISIBLE);
        				tvItemDescriptionManufacturer.setVisibility(View.VISIBLE);
        				tvCategory.setVisibility(View.VISIBLE);
        				ivItem.setVisibility(View.VISIBLE);
        				tvCategoryColor.setVisibility(View.VISIBLE);
        			}
        			v.setBackgroundColor(Color.argb(itemAlphaWidth, 0, 185, 10));
        			
        		} else if (padding < 0 ) {
        			itemAlphaWidth = (int) ((Math.abs(padding)) * itemAlphaWidthFactor);
        			itemAlpha = 255 - itemAlphaWidth;
        			
        			if (itemAlpha <= 0) {
        				tvAmountMeasure.setTextColor(Color.argb(0, 0, 0, 0));
        				tvPriceMeasure.setTextColor(Color.argb(0, 0, 0, 0));
        				tvItem.setTextColor(Color.argb(0, 0, 0, 0));
        				tvItemDescriptionManufacturer.setTextColor(Color.argb(0, 0, 0, 0));
        				tvCategory.setTextColor(Color.argb(0, 0, 0, 0));
        				ivItem.setAlpha(0);
        				tvCategoryColor.getBackground().setAlpha(0);
        			} else {
        				tvAmountMeasure.setTextColor(Color.argb(itemAlpha, 0, 0, 0));
        				tvPriceMeasure.setTextColor(Color.argb(itemAlpha, 0, 0, 0));
        				tvItem.setTextColor(Color.argb(itemAlpha, 0, 0, 0));
        				tvItemDescriptionManufacturer.setTextColor(Color.argb(itemAlpha, 0, 0, 0));
        				tvCategory.setTextColor(Color.argb(itemAlpha, 0, 0, 0));
        				ivItem.setAlpha(itemAlpha);
        				tvCategoryColor.getBackground().setAlpha(itemAlpha);
        			}
        			
        			if (itemAlphaWidth > 255) {
        				itemAlphaWidth = 255;
        				itemSwiped = true;
        				
        				tvAmountMeasure.setVisibility(View.INVISIBLE);
        				tvPriceMeasure.setVisibility(View.INVISIBLE);
        				tvItem.setVisibility(View.INVISIBLE);
        				tvItemDescriptionManufacturer.setVisibility(View.INVISIBLE);
        				tvCategory.setVisibility(View.INVISIBLE);
        				ivItem.setVisibility(View.INVISIBLE);
        				tvCategoryColor.setVisibility(View.INVISIBLE);
        				
        				v.scrollTo(0, 0);
        				
        				tvAddRemoveItem.setText(tvItem.getText().toString() + "\n" + context.getResources().getString(R.string.remove_from_list));
        				tvAddRemoveItem.setVisibility(View.VISIBLE);
        			} else {
        				tvAddRemoveItem.setVisibility(View.INVISIBLE);
        				v.scrollTo(Math.abs(padding), 0);
        				
        				tvAmountMeasure.setVisibility(View.VISIBLE);
        				tvPriceMeasure.setVisibility(View.VISIBLE);
        				tvItem.setVisibility(View.VISIBLE);
        				tvItemDescriptionManufacturer.setVisibility(View.VISIBLE);
        				tvCategory.setVisibility(View.VISIBLE);
        				ivItem.setVisibility(View.VISIBLE);
        				tvCategoryColor.setVisibility(View.VISIBLE);
        			}
        			v.setBackgroundColor(Color.argb(itemAlphaWidth, 235, 0, 29));
        		}
        	}
        	
        }
        
        return gDetector.onTouchEvent(event);
    }


    public GestureDetector getDetector()
    {
        return gDetector;
    }       

	public void startEditItem(String Item) {
		Intent intent = new Intent(context, EditItem.class);
		intent.putExtra("Item", Item);
		context.startActivity(intent);
	}

}
